<template>
	<view class="chat-list">
		<!-- 时间分隔 -->
		<view v-if="formatTime" class="time-separator">
			{{ formatTime }}
		</view>

		<!-- 消息内容 -->
		<view :class="['message-wrapper', { self: isSelf }]">
			<!-- 头像 -->
			<image class="user-img" :src="item.avatar" mode="aspectFill" @click="goToDetail(item.userId)"></image>
			<!-- 消息气泡 -->
			<view class="chat-bubble">
				{{ item.content }}
			</view>
		</view>
	</view>
</template>

<script>
import $time from '@/utils/lib/time.js';

export default {
	name: 'MessageItem',
	props: {
		item: {
			type: Object,
			required: true
		},
		pretime: {
			type: [Number, String],
			default: null
		},
		userId: {
			type: [Number, String],
			required: true
		}
	},
	computed: {
		// 判断是否是自己发的消息
		isSelf() {
			return this.item.userId === this.globalData.userId;
		},
		// 格式化时间
		formatTime() {
			if (!this.item || !this.item.createTime) return '';
	
			const current = new Date(this.item.createTime).getTime();
			if (isNaN(current)) return '';
	
			const prev = this.pretime ? new Date(this.pretime).getTime() : null;
			if (prev !== null && isNaN(prev)) return '';
	
			return $time.getChatTime(current, prev);
		}
	},
	methods: {
		// 新增方法：点击头像跳转到好友详情页
		goToDetail(userId) {
			const currentUserId = getApp().globalData.userId;
				
			// 判断是否是自己
			if (userId === currentUserId) {
				uni.navigateTo({
					url: '/pages/mine/user-space'
				});
			}else{
				uni.navigateTo({
					url: `/pages/paper/friend_profile?userId=${userId}`
				});
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.chat-list {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.time-separator {
	font-size: 24rpx;
	color: #999;
	margin: 20rpx 0;
	text-align: center;
}

.message-wrapper {
	display: flex;
	align-items: start;
	margin: 20rpx 0;
	max-width: 70%;
	width: auto;

	.user-img {
		width: 80rpx;
		height: 80rpx;
		border-radius: 40rpx;
	}

	.chat-bubble {
		max-width: 500rpx;
		padding: 20rpx;
		background-color: #f0f0f0;
		border-radius: 16rpx;
		margin-left: 20rpx;
		font-size: 28rpx;
		word-break: break-word;
	}

	&.self {
		flex-direction: row-reverse;

		.chat-bubble {
			background-color: #07c160;
			color: white;
			margin-left: 0;
			margin-right: 20rpx;
		}
	}
}
</style>